#!/bin/bash

MOUNT_POINT=$(df -t btrfs --output="source,target" | tail -n +2 | awk '{print $1";"$2}')
#MOUNT_POINT=( "/dev/nvme0n1p5;/" \
#	"/dev/nvme0n1p5;/media/Build" \
#	"/dev/nvme0n1p5;/media/Games")
TMP_DIR="/tmp/btrfs-snapshot"
SNAP_DIR="Arch-Snap"

function func_prepare() {
	# Stop thunder first.
	export THUNDER_BIN=/opt/Xware/portal
	${THUNDER_BIN} -s 2> /dev/null
		export THUNDER_STAT=$?
	if [[ ${THUNDER_STAT} == "0" ]]; then
		echo "[Thunder is running. Stopped.]"
	fi

	echo -e -n "\n"
	echo -e "\E[1;32mStart btrfs snapshot.\E[0m"

	# Exclude unnecessary mount point.
	export MOUNT_POINT=($(
		for LINE in ${MOUNT_POINT[@]}; do
			echo ${LINE} | grep -e '/btrfsdata'
		done
	))
	sync
	sync
}

function func_post() {
	echo -e -n "\n"
	echo -e "\E[1;32mBtrfs snapshot finished.\E[0m"

	if [[ ${THUNDER_STAT} == "0" ]]; then
		echo "[Restore thunder.]"
		${THUNDER_BIN} 2> /dev/null
	fi
}

function func_snap() {
	BTRFS_DEV=${1}
	BTRFS_MNT=${2}
	echo -e -n "\n"
	TMP_MNT="${TMP_DIR}/$(echo ${BTRFS_DEV} | awk -F '/' '{print $NF}')"
	SUBVOL="$(btrfs subvolume show ${BTRFS_MNT} | \
		awk '{if ($1 == "Name:") print $NF }')"
	SNAP_NAME="${TMP_MNT}/${SNAP_DIR}/${SUBVOL}-$(date +%Y-%m-%d)"

	mkdir -p ${TMP_MNT}
	mount -t btrfs ${BTRFS_DEV} ${TMP_MNT}
	sleep 1
	mkdir -p ${TMP_MNT}/${SNAP_DIR}
	DEL_STAT=0
	if [[ -d "${SNAP_NAME}" ]]; then
		btrfs subvolume delete "${SNAP_NAME}"
		DEL_STAT=$?
	fi
	if [ ${DEL_STAT} -ne 0 ]; then
		echo -e -n "\E[1;31mDelete snapshot for ${BTRFS_MNT} failed,\E[0m"
		echo -e "\E[1;31mskip snapshot.\E[0m"
		sleep 1
		umount ${TMP_MNT}
		rmdir ${TMP_MNT}
		return
	fi
	btrfs subvolume snapshot -r "${BTRFS_MNT}" "${SNAP_NAME}"
	SNP_STAT=$?
	sync
	# Delete old btrfs snapshot since 6 mouth ago.
	# TIME_LINE is the unix time of 6 mouth ago.
	TIME_LINE=$(( $(date +%s) - 15552000 ))
	for SNAPS in $(ls -1 ${TMP_MNT}/${SNAP_DIR}/ | grep "${SUBVOL}" ); do
		TIME_SNAP=$(date +%s -d $(echo "${SNAPS}" | \
			awk -F '-' '{print $(NF-2)"-"$(NF-1)"-"$NF}' ))
		if [ ${TIME_SNAP} -lt ${TIME_LINE} ]; then
			btrfs subvolume delete "${TMP_MNT}/${SNAP_DIR}/${SNAPS}"
		fi
	done
	sync
	sleep 1
	umount ${TMP_MNT}
	rmdir ${TMP_MNT}
	if [ ${SNP_STAT} -eq 0 ]; then
		echo -e "\E[1;36mSnapshot for ${BTRFS_MNT} finished.\E[0m"
	else
		echo -e "\E[1;31mSnapshot for ${BTRFS_MNT} failed.\E[0m"
	fi
}

func_prepare
mkdir -p ${TMP_DIR}
for LINE in ${MOUNT_POINT[@]}; do
	func_snap $(echo ${LINE} | awk -F ';' '{print $1}') \
		$(echo ${LINE} | awk -F ';' '{print $NF}')
done
rmdir ${TMP_DIR}
func_post

